const api = require('../../api/index')
const app = getApp()
// pages/search/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
      SearchValue:"",
      hotsongList:[],
      searchlist:[],
      timer : null,
      ids:"",
      songcanok:[],
  },
getsongsuggest(SearchValue){
    api.getsearch({keywords:SearchValue})
    .then(
      content => {
        console.log(content);
        let {code, result:{songs}} = content;
        if(code == 200) {
            // 赋值
            this.setData({
              searchlist:songs
            })
        }
      }
    )
  },

  // 还要做一下防抖
  handsearch:function(event){
    if (this.timer) {
      clearInterval(this.timer)
    }
    this.SearchValue = event.detail.value
    console.log(this.SearchValue);
    this.timer = setTimeout(()=>{
      this.getsongsuggest(this.SearchValue)
    },2000)
   
    if (!this.SearchValue.length) {
      this.setData({
        searchlist:[]
      })
      clearInterval(this.timer)
      return
    }
   
},

//点击热门搜索赋值给输入框
hotsearch(event){
  const searchWord = event._relatedInfo.anchorRelatedText
  this.setData({
    SearchValue : searchWord
  })

  this.getsongsuggest(searchWord)
},
playdata(e){
 
  let ids = e.currentTarget.dataset.ids
  this.songcanplay(ids)
  let success = this.data.songcanok.success
  let msg = this.data.songcanok.message
  if (!success) {
    wx.showModal({
      title: '提示',
      content: msg,
    })
    return
  }
  wx.navigateTo({
    url: `../songdetail/songdetail?ids=${ids}`,
  })
},
 // 判断歌曲是否可以播放
 songcanplay(ids){
  api.getsongok({id:ids})
  .then(
    content=>{
      this.setData({
          songcanok:content
      })
    }
  )
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    api.gethotsong()
    .then(
        content => {
          let {code, data} = content;
          let hotsongL = data.slice(0, 12)
          // console.log(hotsongL);
          if(code == 200) {
              // 赋值
              this.setData({
                hotsongList:hotsongL
              })
          }
        }
    )

    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})